import store from '@/store'
import axios from 'axios'
import {Message, Loading} from 'element-ui'
import util from '@/assets/utils/zhzf-util'

// 创建一个错误
function errorCreate(msg) {
  const error = new Error(msg);
  errorLog(error);
  // throw error
}

// 记录和显示错误
function errorLog(error) {
  Loading.service().close();
  // 添加到日志
  store.dispatch('d2admin/log/push', {
    message: '数据请求异常',
    type: 'danger',
    meta: {
      error
    }
  })
  // 打印到控制台
  if (process.env.NODE_ENV === 'development') {
    util.log.danger('>>>>>> Error >>>>>>');
    console.log(error)
  }
  // // 显示提示
  // Message({
  //   message: error.message,
  //   type: 'error',
  //   showClose: true,
  //   duration: 5 * 1000
  // })
}

const service = axios.create({
  baseURL: '/api',
  timeout: 5000 // 请求超时时间
});

// 请求拦截器
service.interceptors.request.use(
  config => {
    let token = util.cookies.get('token');
    config.headers['X-Token'] = token;
    return config
  },
  error => {
    // 发送失败
    errorLog(error);
    return Promise.reject(error)
  }
);

// 响应拦截器
service.interceptors.response.use(
  response => {
    const dataAxios = response.data;
    // 这个状态码是和后端约定的
    const {code} = dataAxios;
    if (code === undefined) {
      // 如果没有 code 代表这不是项目后端开发的接口 比如可能是 D2Admin 请求最新版本
      return dataAxios
    } else {
      switch (code) {
        case 0:
          return dataAxios.data;
        case 20001://登录失效
          setTimeout(() => {
            store.dispatch('d2admin/account/logout');
          }, 1000)
          errorCreate(`${dataAxios.msg}`);
          break;
        default:
          errorCreate(`${dataAxios.msg}`);
          break;
      }
    }
  },
  error => {
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = '请求错误';
          break;
        case 401:
          error.message = '未授权，请登录';
          break;
        case 403:
          error.message = '拒绝访问';
          break;
        case 404:
          error.message = `请求地址出错: ${error.response.config.url}`;
          break;
        case 408:
          error.message = '请求超时';
          break;
        case 500:
          error.message = '服务器内部错误';
          break;
        case 501:
          error.message = '服务未实现';
          break;
        case 502:
          error.message = '网关错误';
          break;
        case 503:
          error.message = '服务不可用';
          break;
        case 504:
          error.message = '网关超时';
          break;
        case 505:
          error.message = 'HTTP版本不受支持';
          break;
        default:
          break
      }
    }
    errorLog(error);
    return Promise.reject(error)
  }
)

export default {
  get(url, data, loading) {
    data = data || {};
    return service({url, data, method: 'get', loading});
  },
  post(url, data, isLoading) {
    data = data || {};
    let param = {url, data, method: 'post'};
    if(data && data.currentPage){
      data.pageIndex = data.currentPage;
      delete data.currentPage;
    }
    if (isLoading) {
      param.loading = {
        type: 'loading',
        options: {
          fullscreen: true,
          lock: true,
          text: '正在加載...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
    return service(param);
  }
}
